import Cookies from "js-cookie";
import qs from "qs";
import { encodeBase64 } from "@/utils/base64";
import { CLIENT_ID } from "@/config/config";
import { os, storage } from "hdzk-tools";
import { showDialog } from "vant";
import dayjs from "dayjs";
import utc from "dayjs/plugin/utc";

dayjs.extend(utc);

export function removeToken() {
	Cookies.remove("ACCESS__TOKEN__");
	localStorage.removeItem("token");
	sessionStorage.removeItem("token");
	storage.removeToken();
}
/**
 * 获取url中的指定参数(不使用hash模式)
 */
export function getQueryString(name: string) {
	const url = new URL(window.location.href);
	return url.searchParams.get(name);
}

/**
 * 跳转飞书登录
 */
export function goFsAuthorize() {
	removeToken();
	const redirect_uri = location.origin;
	/** url携带的参数 */
	const urlSearch = location.href.includes("?") ? location.href.split("?")[1] : undefined;
	// 飞书认证需要将pathname进行base64加密
	const hash = urlSearch ? encodeBase64(`${location.pathname}?${urlSearch}`) : encodeBase64(location.pathname);
	const params = {
		client_id: CLIENT_ID,
		redirect_uri,
		response_type: "code",
		requestOrigin: "FS",
		hash
	};
	window.location.href = import.meta.env.VITE_LOGIN_URL + `/oauth2/authorize?${qs.stringify(params)}`;
}
/**
 * 跳转登录页
 */
export function goAuthorize() {
	const pathname = location.pathname;
	removeToken();
	const redirect_uri = location.origin;
	const params = {
		client_id: CLIENT_ID,
		redirect_uri,
		response_type: "code",
		hash: encodeBase64(pathname)
	};
	window.location.href = import.meta.env.VITE_LOGIN_URL + `/oauth2/authorize?${qs.stringify(params)}`;
}

/** 判断hash模式 URL中的参数是否存在 */
export function hasHashParam(name: string) {
	const url = new URL(window.location.href);
	return url.hash.indexOf(name) !== -1;
}

/** 关闭当前窗口 */
export function closeWindow() {
	// 在飞书内
	if (os.isFs) {
		window.h5sdk
			.ready(() => {
				// ready方法不需要每次都调用
				window.tt.closeWindow({
					fail() {
						throw new Error("关闭窗口失败，请手动关闭");
					}
				});
			})
			.catch((error: any) => {
				console.error("sdk error:", error.message || error);
				showDialog({
					message: error.message || error || "SDK初始化失败"
				});
			});
	} else {
		window.close();
	}
}

/**
 * 格式化日期
 * @param {string|Date|number} date - 要格式化的日期字符串或日期对象
 * @param {string} [formatStr="YYYY-MM-DD hh:mm:ss"] - 格式化字符串，默认为 "YYYY-MM-DD hh:mm:ss"
 * @param {string} [nullValue="--"] - 空值占位符
 * @returns {string} 格式化后的日期字符串，如果传入的日期为空，则返回 "--"
 */
export const formatDate = (
	date: string | Date | number,
	formatStr: string = "YYYY-MM-DD hh:mm:ss",
	nullValue: string = "-",
	utc: boolean = false
) => {
	return date ? (utc ? dayjs(date).utc().format(formatStr) : dayjs(date).format(formatStr)) : nullValue;
};

/** 获取对象中指定属性 */
export const getObjectProperty = (obj: any, keys: string[]) => {
	let result: { [key: string]: any } = {};
	for (let key of keys) {
		result[key] = obj.hasOwnProperty(key) ? obj[key] : undefined;
	}
	return result;
};
